package com.shijie.sjoj.service.box;

import com.shijie.sjoj.model.pojo.base.CodeType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 判题机创建器类
 *
 * @author ZSJ
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JudgeWorkerCreator {

    /**
     * SpringBootBean上下文
     */
    private final ApplicationContext applicationContext;

    /**
     * 判题机Map
     */
    private static ConcurrentHashMap<String, JudgeWorker> BeansMap;

    /**
     * 创建判题机
     *
     * @param codeType CodeType
     * @return JudgeWorker
     */
    public JudgeWorker createJudgeWorker(CodeType codeType) {
        // 格式化BeanMap
        if (null == BeansMap) {
            BeansMap = new ConcurrentHashMap<>();
        }
        if (BeansMap.isEmpty()) {
            BeansMap.putAll(applicationContext.getBeansOfType(JudgeWorker.class));
        }
        // 开始获取创建判题机
        for (JudgeWorker v : BeansMap.values()) {
            // JudgeWorkerCodeType.value()的默认值为CodeType.Java
            if (v.getClass().getAnnotation(JudgeCodeType.class).value().equals(codeType)) {
                // 返回对应语言的判题机
                return v;
            }
        }
        // 没有找到对应语言的判题机，返回null
        log.error("该类型的Bean未找到，可能未定义该程序语言及判题实现类或未添加程序语言标识注解");
        return null;
    }


}
